package com.fz.study.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.fz.study.project.entity.Result;
import com.fz.study.project.entity.User;
import com.fz.study.project.entity.dto.LoginFormDTO;
import com.fz.study.project.entity.dto.UserDTO;
import com.fz.study.project.exception.BizException;
import com.fz.study.project.mapper.TbUserMapper;
import com.fz.study.project.service.ITbUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fz.study.project.utils.JwtUtils;
import com.fz.study.project.utils.RegexUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.fz.study.project.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-02-25
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<TbUserMapper, User> implements ITbUserService {

    private final HttpServletRequest request;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Object sendCode(String phone) {
//        校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //        不符合返回错误信息
            BizException.throwBizException("手机号格式错误");
        }
//        生成验证码
        String code = RandomUtil.randomNumbers(6);
//        保存验证码
//        Map<String,Object> claims = new HashMap<>();
//        claims.put("phone",phone);
//        claims.put("code",code);
//        将验证码存储到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
//        发送验证码
        log.info("验证码信息为：{}", code);
//        返回
        return Result.success();
    }

    @Override
    public Result login(LoginFormDTO loginFormDTO) {

        String phone = loginFormDTO.getPhone();
//        校验电话号码是否正确
        if (RegexUtils.isPhoneInvalid(phone)) {
            BizException.throwBizException("手机号码有误！");
        }
////        校验验证码是否正确
//        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
////        比较二者code信息是否一致
//        if (!code.equals(loginFormDTO.getCode())){
//            BizException.throwBizException("二次验证码不一致！");
//        }
//        根据手机号查询用户
//        User user = lambdaQuery().eq(User::getPhone, phone).one();
        User user = query().eq("phone", phone).one();
//        不存在添加用户
        if (user == null) {
            user = createUserWithPhone(phone);
        }
//        使用jwt生成token，作为登录令牌
        Map<String, Object> claims1 = new HashMap<>();
        claims1.put("nickname", user.getNickName());
        String token = JwtUtils.generateJwt(claims1);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
//        将user对象装变成hash存储
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
//                自定义所有类型都转字符串
//                setIgnoreNullValue(true)忽略空的值
//                setFieldValueEditor修改字段名和字段值的类型
                        .setIgnoreNullValue(true).setFieldValueEditor((fieldname, fieldValue) -> {
                                    if (fieldValue == null) {
                                        return null;
                                    }
                                    return fieldValue.toString();
                                }


                        ));
//        tokenkey
        String tokenKey = LOGIN_USER_KEY + token;
//        将信息存储到redis中
        stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
//        设置有效期
        stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
//        StpUtil.login(user.getNickName());
        return Result.success(token);
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName("user_" + phone);
        save(user);
        return user;
    }
}
